import { Main } from "../constant";

// items: [{ connectId: '', db: [], spinning: false }]
export default function reducer(state = { active: '', items: [] }, { type, data }) {
    state = {active: state.active, items: [...state.items]};

    if (type === Main.ADD) {
        let i = state.items.findIndex(x => x.connectId === data.connectId && x.db.id === data.db.id);

        if (i === -1) {
            data = {...data, spinning: true};
            state.items.push(data);
        }
        
        state.active = `${data.connectId}_${data.db.id}`;
    }
    if (type === Main.CHANGE) state.active = data;
    if (type === Main.REMOVE) {
        let f = x => data !== `${x.connectId}_${x.db.id}`,
            i = state.items.findIndex(f), o = null;
        i = i - 1 > -1 ? i - 1 : i;
        state.items = state.items.filter(f);
        if (state.items.length > 0) {
            if ((o = state.items[i])) state.active = `${o.connectId}_${o.db.id}`;
            else state.active = `${state.items[0].connectId}_${state.items[0].db.id}`;
        }
    }
    if (type === Main.LOADTABLE) {
        let o = null;
        if ((o = state.items.find(x => `${x.connectId}_${x.db.id}` === data.active))) {
            console.log(data.tables)
            o.tables = data.tables;
            o.spinning = false;
        }
    }

    return state;
}